// Copyright (c) 2021 G_night

/*
使用方法
*/
package main

import (
	"agopool"
	"fmt"
	"sync/atomic"
	"time"
)

func main() {
	//demo1() // 常规goroutine
	//demo2() // 使用Agopool
	demo3() // 非阻塞Agopool
}

func demo1() {
	var sum int64 = 0
	for i := 1; i < 1000000; i++ {
		go func() {
			atomic.AddInt64(&sum, 1)
		}()
	}
	fmt.Println("demo1 = ", sum)
}

func demo2() {
	pool := agopool.NewPool()
	var sum int64 = 0
	add := func(v ...interface{}) {
		atomic.AddInt64(&sum, 1)
	}
	for i := 1; i < 1000000; i++ {
		pool.Put(add, nil)
	}
	pool.Close()
	fmt.Println("demo2 = ", sum)
}

func demo3() {
	// 需要非阻塞才能设置超时方法
	pool := agopool.NewNotBlockPool(10)
	after := func(v ...interface{}) {
		fmt.Println("超时啦")
	}
	pool.SetTimeoutAfterFunc(agopool.TimeoutFunc{
		Handler: after,
		Params:  nil,
	})
	var sum int64 = 0
	add := func(v ...interface{}) {
		fmt.Println("sum = ", atomic.AddInt64(&sum, 1))
		<-time.After(5 * time.Second)
	}
	for i := 1; i <= 15; i++ {
		ok, _ := pool.Put(add, nil)
		if !ok {
			fmt.Println("丢弃了一个 i = ", i)
		}
	}
	pool.Close()
}
